<template>
  <view class="blue-wifi-container">
    <!-- 导航栏 -->
    <NavBar title="蓝牙配网" :showBack="true" />

    <!-- 蓝牙状态卡片 -->
    <view class="status-card">
      <view class="status-icon" :class="{ 'connected': connected }">
        <image :src="connected ? '/static/GLOBAL.png' : '/static/GLOBAL.png'"></image>
      </view>
      <view class="status-text">
        <text class="status-title">{{ statusText }}</text>
        <text class="status-desc">{{ statusDesc }}</text>
      </view>
    </view>

    <!-- 设备列表 -->
    <view v-if="!connected && deviceList.length > 0" class="device-list">
      <view class="section-title">可用设备</view>
      <view class="device-item" v-for="(device, index) in deviceList" :key="index" @tap="connectDevice(device)">
        <view class="device-name">{{ device.name || '未知设备' }}</view>
        <view class="device-info">
          <text class="device-id">{{ formatDeviceId(device.deviceId) }}</text>
          <text class="rssi">信号: {{ device.RSSI }} dBm</text>
        </view>
      </view>
    </view>

    <!-- 设备信息 -->
    <view v-if="deviceInfo" class="device-info">
      <view class="section-title">设备信息</view>
      <view class="info-list">
        <view class="info-item">
          <text class="label">设备名称</text>
          <text class="value">{{ deviceInfo.name || '未知设备' }}</text>
        </view>
        <view class="info-item">
          <text class="label">设备ID</text>
          <text class="value uuid">{{ formatDeviceId(deviceInfo.deviceId) }}</text>
        </view>
        <view class="info-item">
          <text class="label">MAC地址</text>
          <text class="value">{{ deviceInfo.macAddress || '未获取' }}</text>
        </view>
        <view class="info-item">
          <text class="label">信号强度</text>
          <text class="value">{{ deviceInfo.RSSI || '-' }} dBm</text>
        </view>
        <view class="info-item">
          <text class="label">连接状态</text>
          <text class="value">{{ connected ? '已连接' : '未连接' }}</text>
        </view>
      </view>
    </view>

    <!-- WiFi配置表单 -->
    <view v-if="connected" class="wifi-form">
      <view class="section-title">WiFi配置</view>
      
      <!-- WiFi选择 -->
      <view class="input-group" @tap="scanWifi">
        <view class="input-label">WiFi</view>
        <input type="text" disabled :value="wifiForm.ssid" placeholder="点击选择WiFi" />
        <view class="input-icon">
          <text class="iconfont icon-wifi"></text>
        </view>
      </view>
      
      <!-- 密码输入 -->
      <view class="input-group">
        <view class="input-label">密码</view>
        <input 
          :type="showPassword ? 'text' : 'password'" 
          v-model="wifiForm.password" 
          placeholder="请输入WiFi密码" 
        />
        <view class="input-icon" @tap="togglePasswordVisibility">
          <text class="iconfont" :class="showPassword ? 'icon-eye' : 'icon-eye-off'"></text>
        </view>
      </view>

      <!-- 加密类型选择 -->
      <view class="input-group">
        <view class="input-label">加密类型</view>
        <picker @change="onEncryptionChange" :value="encryptionIndex" :range="encryptionTypes">
          <view class="picker">{{ encryptionTypes[encryptionIndex] }}</view>
        </picker>
      </view>
      
      <!-- 配置按钮 -->
      <button 
        class="config-btn" 
        :disabled="!wifiForm.ssid || isLoading" 
        :loading="isLoading"
        @tap="configWifi"
      >
        确认配置
      </button>
    </view>

    <!-- 调试按钮区域 - 已连接状态 -->
  <!-- 调试按钮区域 - 已连接状态 -->
<view class="debug-btns" v-if="connected">
  <button class="debug-btn" @tap="testScanWifi">测试扫描</button>
  <button class="debug-btn" @tap="testAlternateCommand">发送测试命令</button>
  <button class="debug-btn" @tap="selectTestWifi">选择测试WiFi</button>
  <button class="debug-btn" @tap="configUpgradeAP">直接配置AP</button>
</view>

    <!-- 重新扫描蓝牙按钮 -->
    <button 
      v-if="!connected" 
      class="init-btn" 
      :disabled="isLoading" 
      :loading="isInitializing"
      @tap="initBluetooth"
    >
      {{ bluetoothEnabled ? '扫描设备' : '初始化蓝牙' }}
    </button>

    <!-- WiFi列表弹窗 -->
    <view class="wifi-popup" v-if="showWifiList">
      <view class="wifi-popup-mask" @tap="showWifiList = false"></view>
      <view class="wifi-popup-content">
        <view class="wifi-popup-header">
          <text class="wifi-popup-title">选择WiFi</text>
          <text class="wifi-popup-close" @tap="showWifiList = false">×</text>
        </view>
        
        <!-- WiFi列表 -->
        <scroll-view class="wifi-list" scroll-y>
          <view v-if="isScanning" class="scanning-tips">
            <view class="loading-spinner"></view>
            <text>扫描中...</text>
          </view>
          <view v-else-if="wifiList.length === 0" class="empty-tips">
            <text>未找到WiFi网络</text>
            <button class="refresh-btn" @tap="scanWifi">重新扫描</button>
          </view>
          <view 
            v-else
            v-for="(wifi, index) in wifiList" 
            :key="index"
            class="wifi-item"
            @tap="selectWifi(wifi)"
          >
            <view class="wifi-name">{{ wifi.ssid }}</view>
            <view class="wifi-desc">
              <text class="wifi-strength" :style="{ width: getSignalWidth(wifi.rssi) }"></text>
              <text v-if="wifi.secure" class="wifi-secure">加密</text>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 加载动画组件 -->
    <view class="loading-overlay" v-if="isLoading">
      <view class="loading-content">
        <view class="loading-spinner"></view>
        <text class="loading-text">{{ loadingText }}</text>
      </view>
    </view>

    <!-- 错误提示模态框 -->
    <view class="error-modal" v-if="showError">
      <view class="error-content">
        <view class="error-title">错误提示</view>
        <view class="error-message">{{ errorMessage }}</view>
        <button class="error-btn" @tap="closeError">确定</button>
      </view>
    </view>
  </view>
</template>

<script setup>
// 修复的导入部分
import { ref, computed, onMounted, onBeforeUnmount, inject } from 'vue'
import NavBar from '@/components/NavBar/NavBar.vue'
import { delay } from '@/utils/coroutine'
import system from '@/utils/system'
import useExecutorStarter from '@/utils/useExecutorStarter'
import { hex2u8, u82hex, strToHex, hexToStr } from '@/utils/converter'
// 导入 store
import { useHardwareStore } from '@/stores'
// 在组件顶部添加防抖控制变量
const isRegistering = ref(false)

// 在setup中获取hardwareStore
const hardwareStore = useHardwareStore()


// TextEncoder 兼容性处理
if (typeof TextEncoder === 'undefined') {
  const TextEncoder = function() {};
  TextEncoder.prototype.encode = function(str) {
    const buf = new ArrayBuffer(str.length);
    const bufView = new Uint8Array(buf);
    for (let i = 0; i < str.length; i++) {
      bufView[i] = str.charCodeAt(i);
    }
    return bufView;
  };
  globalThis.TextEncoder = TextEncoder;
}


// 常量定义 - 与固件中定义的命令保持一致
const CMD = {
  SCAN_WIFI: ':scan',  // 扫描WiFi命令
  CONFIG_WIFI: ':',    // 配置WiFi命令前缀，后面直接跟SSID,PASSWORD,ENCRYPT_TYPE
}

// 响应码定义 - 与固件中定义的响应保持一致
const RESPONSE = {
  WIFI_LIST: 'FFFF01', // WiFi列表响应
  CONFIG_RESULT: 'FFFF02', // 配网结果响应
}

// 系统信息
const statusBarHeight = ref(system.getStatusBarHeight())

// 蓝牙状态
const bluetoothEnabled = ref(false)
const discovering = ref(false)
const connected = ref(false)
const deviceInfo = ref(null)
const deviceList = ref([])

// 这里的UUID需要和硬件端的UUID一致，从硬件代码中可以看到使用的是TXW81X芯片的标准UUID
// 动态UUID变量 - 将从设备中获取
const serviceUUID = ref('')          // 主服务UUID  
const writeCharUUID = ref('')        // 写特征值UUID
const readCharUUID = ref('')        // 读特征值UUID
const notifyCharUUID = ref('')       // 通知特征值UUID

// WiFi表单
const wifiForm = ref({
  ssid: '',
  password: ''
})
const showPassword = ref(false)
const encryptionTypes = ['WPA-PSK', 'NONE', 'WPA2-PSK', 'WPA/WPA2-PSK']
const encryptionIndex = ref(0)

// 状态控制
const isInitializing = ref(false)
const isScanning = ref(false)
const isLoading = ref(false)
const loadingText = ref('处理中...')
const showWifiList = ref(false)
const showError = ref(false)
const errorMessage = ref('')

// WiFi列表
const wifiList = ref([])

// 重试机制
const maxRetries = 3
const currentRetry = ref(0)

// 计算属性
const statusText = computed(() => {
  if (connected.value) return '已连接设备'
  if (discovering.value) return '正在搜索设备'
  if (bluetoothEnabled.value) return '蓝牙已启用'
  return '蓝牙未启用'
})

const statusDesc = computed(() => {
  if (connected.value) return `已连接到"${deviceInfo.value?.name || '未知设备'}"`
  if (discovering.value) return '正在搜索附近的蓝牙设备'
  if (bluetoothEnabled.value) return '点击扫描按钮开始搜索设备'
  return '请点击初始化按钮启用蓝牙'
})

// 格式化设备ID显示
const formatDeviceId = (deviceId) => {
  if (!deviceId) return '未获取'
  return deviceId.substring(0, 8) + '...' + deviceId.substring(deviceId.length - 8)
}

// 获取信号强度宽度
const getSignalWidth = (rssi) => {
  // 信号强度(-100dBm ~ -30dBm)
  const percent = Math.min(100, Math.max(0, (rssi + 100) * 1.4))
  return `${percent}%`
}

// 错误提示函数
const showErrorMessage = (message) => {
  errorMessage.value = message
  showError.value = true
}

const closeError = () => {
  showError.value = false
  errorMessage.value = ''
}

// 切换密码可见性
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value
}

// 重置蓝牙适配器函数 - 用于解决微信小程序蓝牙API缓存问题
const resetBluetooth = async () => {
  try {
    // 尝试关闭蓝牙适配器
    try {
      await uni.closeBluetoothAdapter()
      console.log('关闭蓝牙适配器成功')
    } catch (err) {
      console.log('关闭蓝牙适配器失败:', err)
    }
    
    // 等待一段时间
    await delay(1000)
    
    // 重新打开蓝牙适配器
    await uni.openBluetoothAdapter()
    console.log('重新打开蓝牙适配器成功')
    
    // 获取状态
    const res = await uni.getBluetoothAdapterState()
    bluetoothEnabled.value = res.available
    discovering.value = res.discovering
    return true
  } catch (error) {
    console.error('重置蓝牙失败:', error)
    bluetoothEnabled.value = false
    discovering.value = false
    uni.showModal({
      title: '提示',
      content: '蓝牙初始化失败，请检查手机蓝牙是否正常',
      showCancel: false
    })
    return false
  }
}

// 调试功能 - 便于排查问题
const debugBluetooth = async () => {
  console.log('当前蓝牙状态:', {
    bluetoothEnabled: bluetoothEnabled.value,
    discovering: discovering.value,
    connected: connected.value,
    deviceInfo: deviceInfo.value,
    serviceUUID: serviceUUID.value,
    writeCharUUID: writeCharUUID.value,
    notifyCharUUID: notifyCharUUID.value
  })

  try {
    const res = await uni.getBluetoothAdapterState()
    console.log('蓝牙适配器状态:', res)
  } catch (err) {
    console.error('获取蓝牙状态失败:', err)
  }
  
  // 检查系统信息
  uni.getSystemInfo({
    success: function(res) {
      console.log('完整系统信息:', res)
    }
  })
  
  uni.showModal({
    title: '调试信息',
    content: '蓝牙调试信息已打印到控制台，请查看日志',
    showCancel: false
  })
}

// 前往系统蓝牙设置
const gotoSystemBluetooth = () => {
  uni.showModal({
    title: '提示',
    content: '是否前往系统蓝牙设置页面?',
    success: function (res) {
      if (res.confirm) {
        // 跳转到系统蓝牙设置页
        uni.openSystemBluetoothSetting()
      }
    }
  })
}

// 生命周期钩子
onMounted(() => {
  // 检查系统环境
  uni.getSystemInfo({
    success: function(res) {
      console.log('系统信息:', res)
      // 检查iOS版本号
      if (res.platform === 'ios') {
        const version = parseInt(res.system.split(' ')[1])
        if (version >= 13) {
          uni.showModal({
            title: '提示',
            content: '在iOS 13及以上版本，您可能需要在设置中对本小程序单独授权蓝牙权限',
            showCancel: false
          })
        }
      }
    }
  })
  
  // 页面加载时重置蓝牙状态
  resetBluetooth().catch(err => {
    console.error('初始页面加载时重置蓝牙失败:', err)
    // 如果重置失败，尝试常规检查
    checkBluetoothStatus()
  })
})

onBeforeUnmount(() => {
  // 断开所有连接
  if (connected.value) {
    disconnectDevice()
  }
})

// 方法
const checkBluetoothStatus = async () => {
  try {
    // 先尝试初始化蓝牙适配器，不管是否已初始化
    try {
      await uni.openBluetoothAdapter()
      console.log('蓝牙适配器初始化成功')
    } catch (err) {
      console.log('蓝牙适配器初始化失败，可能已经初始化:', err)
      // 这里不返回错误，继续尝试获取状态
    }
    
    // 获取状态
    const res = await uni.getBluetoothAdapterState()
    bluetoothEnabled.value = res.available
    discovering.value = res.discovering
  } catch (error) {
    console.error('获取蓝牙状态失败:', error)
    bluetoothEnabled.value = false
    discovering.value = false
    
    // 提供更友好的错误提示
    if (error.errCode === 10000 || error.errno === 1500101) {
      uni.showModal({
        title: '蓝牙未开启',
        content: '请在手机系统设置中开启蓝牙后重试',
        showCancel: false
      })
    }
  }
}

const initBluetooth = async () => {
  if (isInitializing.value || isLoading.value) return
  
  isInitializing.value = true
  isLoading.value = true
  loadingText.value = '初始化蓝牙中...'
  deviceList.value = [] // 清空设备列表
  
  try {
    // 先尝试重置蓝牙适配器
    const resetSuccess = await resetBluetooth()
    
    if (!resetSuccess || !bluetoothEnabled.value) {
      uni.showModal({
        title: '提示',
        content: '请确保手机蓝牙已开启',
        showCancel: false
      })
      return
    }
    
    // 增加延迟，确保蓝牙适配器完全初始化
    await delay(2000)
    
    loadingText.value = '搜索设备中...'
    await startDiscovery()
  } catch (error) {
    console.error('初始化蓝牙失败:', error)
    uni.showModal({
      title: '提示',
      content: '初始化蓝牙失败，请检查手机蓝牙是否开启',
      showCancel: false
    })
  } finally {
    isInitializing.value = false
    isLoading.value = false
  }
}

const startDiscovery = async () => {
  if (discovering.value) return
  
  try {
    discovering.value = true
    
    // 注册发现设备事件
    uni.onBluetoothDeviceFound(onDeviceFound)
    
    // 开始搜索，不过滤服务UUID，扫描所有设备
    await uni.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false
    })
    
    // 自动停止搜索
    setTimeout(async () => {
      if (discovering.value && !connected.value) {
        await stopDiscovery()
        
        if (!connected.value && deviceList.value.length === 0) {
          uni.showToast({
            title: '未找到有效设备',
            icon: 'none'
          })
        }
      }
    }, 20000) // 扫描20秒超时
  } catch (error) {
    console.error('开始搜索设备失败:', error)
    discovering.value = false
  }
}

const stopDiscovery = async () => {
  if (!discovering.value) return
  
  try {
    await uni.stopBluetoothDevicesDiscovery()
    uni.offBluetoothDeviceFound(onDeviceFound)
    discovering.value = false
  } catch (error) {
    console.error('停止搜索设备失败:', error)
  }
}

const onDeviceFound = async (res) => {
  if (!res.devices || res.devices.length === 0) return
  
  // 打印所有设备信息，用于调试
  console.log('所有发现的设备:', res.devices)
  
  // 过滤条件
  const validDevices = res.devices.filter(device => {
    const deviceName = device.name || device.localName || '';
    // 过滤有名称且信号强度足够的设备
    const hasName = !!deviceName;
    const hasGoodSignal = device.RSSI && device.RSSI > -80;
    
    console.log(`设备: ${deviceName}, 信号: ${device.RSSI}, 有效: ${hasName && hasGoodSignal}`);
    
    return hasName && hasGoodSignal;
  });
  
  if (validDevices.length === 0) return
  
  // 将发现的设备添加到列表中（去重）
  validDevices.forEach(device => {
    // 检查设备是否已存在于列表中
    const existingDeviceIndex = deviceList.value.findIndex(d => d.deviceId === device.deviceId);
    
    // 如果设备已存在，更新信息；否则添加到列表
    if (existingDeviceIndex >= 0) {
      deviceList.value[existingDeviceIndex] = device;
    } else {
      deviceList.value.push(device);
    }
  });
  
  // 根据信号强度排序
  deviceList.value.sort((a, b) => (b.RSSI || -100) - (a.RSSI || -100));
}


const getDeviceValues = async () => {
  if (!connected.value || !deviceInfo.value) return;

  try {
    // 读取MAC地址特征值(0x2B15)
    try {
      const macRes = await uni.readBLECharacteristicValue({
        deviceId: deviceInfo.value.deviceId,
        serviceId: deviceInfo.value.serviceId,
        characteristicId: '0x2B15' // MAC地址特征值
      });
      
      console.log('读取MAC地址特征值成功:', macRes);
      const macHexData = u82hex(new Uint8Array(macRes.value));
      const macAddress = hexToStr(macHexData);
      console.log('设备MAC地址:', macAddress);
      
      // 更新设备信息
      deviceInfo.value = {
        ...deviceInfo.value,
        bleMac: macAddress
      };
    } catch (err) {
      console.error('读取MAC地址特征值失败:', err);
    }
    
    // 读取其他特征值
    const res = await uni.readBLECharacteristicValue({
      deviceId: deviceInfo.value.deviceId,
      serviceId: deviceInfo.value.serviceId,
      characteristicId: deviceInfo.value.readCharId || deviceInfo.value.notifyCharId
    });

    console.log('主动读取设备值成功:', res);
    
    // 处理返回的数据
    const hexData = u82hex(new Uint8Array(res.value));
    console.log('设备返回数据(HEX):', hexData);
    
    // 解析数据
    parseDeviceValues(hexData);
  } catch (error) {
    console.error('主动读取设备值失败:', error);
  }
}

const parseDeviceValues = (hexData) => {
  try {
    console.log('开始解析设备值:', hexData);
    
    // 根据硬件数据结构解析
    // 假设数据格式为: [类型(1字节)][长度(1字节)][数据]
    let offset = 0;
    const values = [];
    
    while (offset + 2 <= hexData.length) {
      const type = parseInt(hexData.substr(offset, 2), 16);
      offset += 2;
      
      const length = parseInt(hexData.substr(offset, 2), 16);
      offset += 2;
      
      const valueHex = hexData.substr(offset, length * 2);
      offset += length * 2;
      
      let value;
      switch (type) {
        case 1: // UBLE_VALUE_TYPE_HDL
          value = parseInt(valueHex, 16);
          break;
        case 2: // UBLE_VALUE_TYPE_STRING
          value = hexToStr(valueHex);
          break;
        case 3: // UBLE_VALUE_TYPE_UINT32
          value = parseInt(valueHex, 16);
          break;
        default:
          value = valueHex;
      }
      
      values.push({
        type,
        length,
        value
      });
    }
    
    console.log('解析后的设备值:', values);
    
    // 更新设备信息
    if (values.length >= 5) {
      deviceInfo.value = {
        ...deviceInfo.value,
        ssid: values[1].value,
        password: values[2].value,
        wifiStatus: values[3].value,
        bleMac: values[4].value
      };
    }
  } catch (error) {
    console.error('解析设备值失败:', error);
  }
}

const readDeviceMAC = async () => {
  if (!connected.value || !deviceInfo.value) return;
  
  try {
    console.log('Starting to read device MAC address');
    
    // 使用通知方式获取 MAC 地址
    return new Promise((resolve) => {
      const macTimeout = setTimeout(() => {
        console.log('MAC address not found in notifications');
        if (!deviceInfo.value.macAddress || deviceInfo.value.macAddress === 'Unknown') {
          deviceInfo.value = {
            ...deviceInfo.value,
            macAddress: 'Unknown'
          };
        }
        resolve();
      }, 8000); // 8秒超时
      
      const macListener = (res) => {
        try {
          const textDecoder = new TextDecoder('utf-8');
          const textData = textDecoder.decode(res.value);
          
          console.log('检查通知数据中的MAC地址:', textData);
          
          // 优先使用完整的 MAC 格式匹配
          if (textData.includes('MAC:')) {
            const macMatch = textData.match(/MAC:([0-9A-Fa-f:]+)/);
            if (macMatch && macMatch[1]) {
              const macAddress = macMatch[1];
              console.log('找到MAC地址:', macAddress);
              
              deviceInfo.value = {
                ...deviceInfo.value,
                macAddress: macAddress
              };
              
              clearTimeout(macTimeout);
              uni.offBLECharacteristicValueChange(macListener);
              resolve(macAddress);
            }
          } else {
            // 备用方法：使用正则表达式查找符合MAC地址格式的字符串
            const macRegex = /([0-9A-Fa-f]{2}[:]){5}([0-9A-Fa-f]{2})/;
            const match = textData.match(macRegex);
            
            if (match && match[0]) {
              const macAddress = match[0];
              console.log('找到MAC地址:', macAddress);
              
              deviceInfo.value = {
                ...deviceInfo.value,
                macAddress: macAddress
              };
              
              clearTimeout(macTimeout);
              uni.offBLECharacteristicValueChange(macListener);
              resolve(macAddress);
            }
          }
          
          // 检查是否包含完整设备信息
          if (textData.includes('product_id:') && textData.includes('MAC:') && 
              textData.includes('firmware_version:')) {
            clearTimeout(macTimeout);
            uni.offBLECharacteristicValueChange(macListener);
            resolve();
          }
        } catch (error) {
          console.error('处理MAC地址通知时出错:', error);
        }
      };
      
      uni.onBLECharacteristicValueChange(macListener);
      
      // 发送状态命令以触发返回
      sendCommand('status').catch(err => {
        console.log('发送状态命令失败:', err);
      });
    });
  } catch (error) {
    console.error('readDeviceMAC函数出错:', error);
    deviceInfo.value = {
      ...deviceInfo.value,
      macAddress: 'Error'
    };
  }
};


// Helper function to get device status
const getDeviceStatus = async () => {
  try {
    // Try to request device status
    await sendCommand('status');
    
    // Wait for response
    return new Promise((resolve) => {
      let statusData = '';
      
      const statusListener = (res) => {
        const hexData = u82hex(new Uint8Array(res.value));
        const strData = hexToStr(hexData);
        
        statusData += strData;
        
        if (strData.includes('MAC:') || strData.includes('local:')) {
          uni.offBLECharacteristicValueChange(statusListener);
          resolve(statusData);
        }
      };
      
      uni.onBLECharacteristicValueChange(statusListener);
      
      // Timeout after 3 seconds
      setTimeout(() => {
        uni.offBLECharacteristicValueChange(statusListener);
        resolve(statusData);
      }, 3000);
    });
  } catch (error) {
    console.error('Error getting device status:', error);
    return null;
  }
};

// 检查十六进制数据或字符串是否是MAC地址格式
const isMacAddress = (data) => {
  // 如果是十六进制数据，先转换为字符串
  let str = typeof data === 'string' ? data : hexToStr(data);
  // 标准MAC地址格式：xx:xx:xx:xx:xx:xx (17个字符)
  return /^([0-9A-Fa-f]{2}[:]){5}([0-9A-Fa-f]{2})$/.test(str);
};

const connectDevice = async (device) => {
  if (connected.value) return
  
  isLoading.value = true
  loadingText.value = '正在连接设备...'
  currentRetry.value = 0
  
  try {
    console.log('开始连接设备:', device.deviceId)
    
    // Create connection
    await connectWithRetry(device)
    
    console.log('连接成功, 获取设备信息')
    
    // Get device info
    deviceInfo.value = {
      ...device,
      serviceId: null,
      writeCharId: null,
      notifyCharId: null,
      characteristics: [],
      macAddress: 'Unknown' // 初始设置为未知
    }
    
    // Wait for stable connection
    await delay(2000)
    
    // Get services
    await getDeviceServices()
    
    if (!deviceInfo.value.serviceId || !deviceInfo.value.writeCharId) {
      throw new Error('未找到所需的服务或特征值')
    }
    
    connected.value = true
    
    // 设置通知监听器，专门用于捕获MAC地址
    uni.onBLECharacteristicValueChange((res) => {
      try {
        // 尝试解析为文本字符串
        const rawData = new Uint8Array(res.value);
        const hexData = u82hex(rawData);
        const strData = hexToStr(hexData);
        
        console.log('收到数据(文本):', strData);
        
        // 检查是否包含MAC地址格式字符串
        if (isMacAddress(strData)) {
          console.log('在通知中发现MAC地址:', strData);
          deviceInfo.value.macAddress = strData;
        }
        
        // 如果数据包含MAC地址的其他格式，例如"local:xx:xx:xx:xx:xx:xx"
        const macRegex = /([0-9A-Fa-f]{2}[:]){5}([0-9A-Fa-f]{2})/;
        const macMatch = strData.match(macRegex);
        
        if (macMatch && macMatch[0]) {
          console.log('通知中找到的MAC地址:', macMatch[0]);
          deviceInfo.value.macAddress = macMatch[0];
        }
        
        // 继续处理数据
        parseDeviceData(hexData);
      } catch (err) {
        console.error('处理通知数据时出错:', err);
      }
    });
    
    // 尝试通过多种方式获取MAC地址
    try {
      // 1. 先尝试读取MAC地址特征值 0x2B15
      try {
        console.log('尝试读取特征值 0x2B15');
        const macRes = await uni.readBLECharacteristicValue({
          deviceId: deviceInfo.value.deviceId,
          serviceId: deviceInfo.value.serviceId,
          characteristicId: '0x2B15'
        });
        
        const macData = new Uint8Array(macRes.value);
        const macHexData = u82hex(macData);
        const macAddress = hexToStr(macHexData);
        
        console.log('读取到的MAC地址数据:', macAddress);
        if (isMacAddress(macAddress)) {
          deviceInfo.value.macAddress = macAddress;
          console.log('成功读取MAC地址:', macAddress);
        }
      } catch (err) {
        console.log('无法读取特征值0x2B15:', err);
      }
      
      // 2. 如果上面失败，尝试读取新的MAC地址特征值 0x2B16
      if (deviceInfo.value.macAddress === 'Unknown') {
        try {
          console.log('尝试读取特征值 0x2B16');
          const macRes = await uni.readBLECharacteristicValue({
            deviceId: deviceInfo.value.deviceId,
            serviceId: deviceInfo.value.serviceId,
            characteristicId: '0x2B16'
          });
          
          const macData = new Uint8Array(macRes.value);
          const macHexData = u82hex(macData);
          const macAddress = hexToStr(macHexData);
          
          console.log('从0x2B16读取到的数据:', macAddress);
          if (isMacAddress(macAddress)) {
            deviceInfo.value.macAddress = macAddress;
            console.log('成功从0x2B16读取MAC地址:', macAddress);
          }
        } catch (err) {
          console.log('无法读取特征值0x2B16:', err);
        }
      }
      
      // 3. 如果直接读取特征值都失败，尝试发送命令获取状态
      if (deviceInfo.value.macAddress === 'Unknown') {
        console.log('尝试通过发送状态命令获取MAC地址');
        // 发送status命令，触发设备发送MAC地址通知
        try {
          await sendCommandWithRetry('status', 3);
          console.log('已发送状态命令，等待设备响应');
          
          // 等待一段时间，给设备足够的响应时间
          await delay(2000);
        } catch (err) {
          console.error('发送状态命令失败:', err);
        }
      }
    } catch (err) {
      console.error('获取MAC地址尝试失败:', err);
    }
    
    // 尝试读取其他设备信息
    try {
      // 尝试读取各种常见特征值，遇到错误就跳过
      const characteristics = [
        { uuid: '0x2B12', name: 'SSID', property: 'ssid' },
        { uuid: '0x2B13', name: '密码', property: 'password' },
        { uuid: '0x2B14', name: '加密类型', property: 'encryptionType' }
      ];
      
      for (const char of characteristics) {
        try {
          console.log(`尝试读取${char.name}特征值 ${char.uuid}`);
          const res = await uni.readBLECharacteristicValue({
            deviceId: deviceInfo.value.deviceId,
            serviceId: deviceInfo.value.serviceId,
            characteristicId: char.uuid
          });
          
          const hexData = u82hex(new Uint8Array(res.value));
          let value;
          
          if (char.uuid === '0x2B14') {
            // 加密类型特殊处理
            value = parseInt(hexData.substr(0, 2), 16);
          } else {
            // 其他值当字符串处理
            value = hexToStr(hexData);
          }
          
          console.log(`设备${char.name}:`, value);
          deviceInfo.value[char.property] = value;
        } catch (err) {
          console.log(`读取${char.name}失败:`, err);
        }
      }
    } catch (err) {
      console.error('读取设备配置信息失败:', err);
    }
    
    // 成功连接提示
    uni.showToast({
      title: '连接成功',
      icon: 'success'
    });
    
    // 停止扫描
    await stopDiscovery();
    
    // 连接成功后再次尝试获取设备状态
    setTimeout(async () => {
      if (deviceInfo.value.macAddress === 'Unknown') {
        console.log('再次尝试获取设备MAC地址');
        try {
          await sendCommandWithRetry('status', 2);
        } catch (err) {
          console.log('第二次发送状态命令失败:', err);
        }
      }
    }, 3000);
    
  } catch (error) {
    console.error('连接设备失败:', error);
    uni.showToast({
      title: '连接设备失败',
      icon: 'none'
    });
    
    // Clear device info on connection failure
    deviceInfo.value = null;
    
    // Try to disconnect potential partial connection
    try {
      if (device && device.deviceId) {
        await uni.closeBLEConnection({
          deviceId: device.deviceId
        });
      }
    } catch (e) {
      console.error('断开失败连接时出错:', e);
    }
  } finally {
    isLoading.value = false;
  }
}

// 带重试的连接函数
const connectWithRetry = async (device) => {
  let attempt = 0
  let lastError = null
  
  while (attempt < maxRetries) {
    try {
      await uni.createBLEConnection({
        deviceId: device.deviceId,
        timeout: 15000 // 连接超时时间15秒
      })
      return // 连接成功，直接返回
    } catch (error) {
      lastError = error
      attempt++
      console.log(`连接尝试 ${attempt} 失败:`, error)
      
      if (attempt < maxRetries) {
        // 每次重试前等待一段时间
        await delay(2000)
      }
    }
  }
  
  // 如果所有尝试都失败，抛出最后一个错误
  throw lastError
}

const getDeviceServices = async () => {
  if (!deviceInfo.value) return;
  
  try {
    console.log('开始获取设备服务列表');
    const res = await uni.getBLEDeviceServices({
      deviceId: deviceInfo.value.deviceId
    });
    
    console.log('设备服务列表:', res.services);
    
    // 查找主服务，这里直接使用发现的主服务
    let primaryService = res.services.find(service => service.isPrimary);
    
    if (!primaryService && res.services.length > 0) {
      // 如果没有明确标记为主服务，尝试使用第一个服务
      console.log('未找到明确标记的主服务，尝试使用第一个服务');
      primaryService = res.services[0];
    }
    
    if (primaryService) {
      deviceInfo.value.serviceId = primaryService.uuid;
      serviceUUID.value = primaryService.uuid;
      console.log('找到服务:', primaryService.uuid);
      await getServiceCharacteristics(primaryService.uuid);
    } else {
      throw new Error('未找到可用服务');
    }
  } catch (error) {
    console.error('获取设备服务失败:', error);
    
    // 友好的错误提示
    uni.showToast({
      title: '设备连接异常，请重试',
      icon: 'none'
    });
    
    // 重置连接状态
    connected.value = false;
    
    throw error;
  }
};

const getServiceCharacteristics = async (serviceId) => {
  if (!deviceInfo.value) return
  
  try {
    console.log('开始获取服务特征值', serviceId)
    const res = await uni.getBLEDeviceCharacteristics({
      deviceId: deviceInfo.value.deviceId,
      serviceId: serviceId
    })
    
    console.log('服务特征值列表:', res.characteristics)
    
    // 保存特征值
    deviceInfo.value.characteristics = res.characteristics
    
    // 打印特征值详情
    res.characteristics.forEach((char, index) => {
      console.log(`特征值 ${index}:`, char.uuid, '属性:', 
                 `读:${char.properties.read}, 写:${char.properties.write}, 通知:${char.properties.notify}`)
    })
    
    // 查找可写特征值 - 使用UUID或属性查找
    let writableChar = res.characteristics.find(char => 
      char.properties.write && 
      (char.uuid.toLowerCase() === '0x2b12' || char.uuid.toLowerCase() === '36000002-0001-0002-0003-010203040506')
    )
    
    // 查找可通知特征值 - 优先使用0x2B16
    let notifyChar = res.characteristics.find(char => 
      char.properties.notify && 
      (char.uuid.toLowerCase() === '0x2b16' || char.uuid.toLowerCase() === '36000004-0001-0002-0003-010203040506')
    )
    
    if (writableChar) {
      deviceInfo.value.writeCharId = writableChar.uuid
      writeCharUUID.value = writableChar.uuid
      console.log('找到可写特征值:', writableChar.uuid)
    } else {
      throw new Error('未找到可写入的特征值')
    }
    
    if (notifyChar) {
      deviceInfo.value.notifyCharId = notifyChar.uuid
      notifyCharUUID.value = notifyChar.uuid
      console.log('找到可通知特征值:', notifyChar.uuid)
      await enableNotify(serviceId, notifyChar.uuid)
    } else {
      console.warn('未找到可通知的特征值')
    }
  } catch (error) {
    console.error('获取服务特征值失败:', error)
    throw error
  }
}

const enableNotify = async (serviceId, characteristicId) => {
  if (!deviceInfo.value) return
  
  try {
    console.log('开始启用通知', characteristicId)
    await uni.notifyBLECharacteristicValueChange({
      deviceId: deviceInfo.value.deviceId,
      serviceId: serviceId,
      characteristicId: characteristicId,
      state: true
    })
    
    console.log('启用通知成功')
    
    // 监听特征值变化
    uni.onBLECharacteristicValueChange(onCharValueChange)
  } catch (error) {
    console.error('启用通知失败:', error)
    throw error
  }
}

const onCharValueChange = (res) => {
  // 处理设备返回的数据
  try {
    // 打印原始数据，帮助调试
    console.log('收到设备原始数据:', res.value);
    
    // 尝试解析为文本字符串
    try {
      const textDecoder = new TextDecoder('utf-8');
      const textData = textDecoder.decode(res.value);
      console.log('收到数据(文本):', textData);
      
      // 首先尝试使用完整格式匹配 MAC 地址
      if (textData.includes('MAC:')) {
        const macMatch = textData.match(/MAC:([0-9A-Fa-f:]+)/);
        if (macMatch && macMatch[1]) {
          const macAddress = macMatch[1];
          console.log('找到MAC地址:', macAddress);
          
          deviceInfo.value = {
            ...deviceInfo.value,
            macAddress: macAddress
          };
        }
      } else {
        // 备用：检查是否包含标准MAC地址格式字符串
        const macRegex = /([0-9A-Fa-f]{2}[:]){5}([0-9A-Fa-f]{2})/;
        const macMatch = textData.match(macRegex);
        
        if (macMatch && macMatch[0]) {
          console.log('通知中找到的MAC地址:', macMatch[0]);
          deviceInfo.value = {
            ...deviceInfo.value,
            macAddress: macMatch[0]
          };
        }
      }
      
      // 检查是否包含产品ID
      if (textData.includes('product_id:')) {
        // 调用设备数据解析函数处理完整响应
        parseDeviceData(textData);
      }
    } catch (e) {
      console.log('文本解析失败:', e);
    }
    
    // 转换为十六进制并尝试解析
    const hexData = u82hex(new Uint8Array(res.value));
    console.log('收到设备数据(HEX):', hexData);
    
    // 解析数据
    parseDeviceData(hexData);
  } catch (error) {
    console.error('处理设备数据失败:', error);
  }
}

const parseDeviceData = (hexData) => {
  try {
    console.log('开始解析设备数据:', hexData);
    
    // 将十六进制转换为字符串(如果它还不是字符串)
    const strData = typeof hexData === 'string' && !hexData.includes(',') ? 
                    hexToStr(hexData) : hexData;
    
    // 检查数据是否包含product_id和MAC格式
    if (strData.includes('product_id:') && strData.includes('MAC:')) {
      console.log('检测到设备信息数据:', strData);
      
      // 使用正则表达式提取设备参数
      const productIdMatch = strData.match(/product_id:([a-zA-Z0-9]+)/);
      const macMatch = strData.match(/MAC:([a-zA-Z0-9:]+)/);
      const firmwareMatch = strData.match(/firmware_version:([a-zA-Z0-9\.]+)/);
      const wifiStatusMatch = strData.match(/wifi:(\w+)/);
      
      // 创建包含提取参数的设备信息对象
      const deviceParams = {
        productId: productIdMatch ? productIdMatch[1] : null,
        macAddress: macMatch ? macMatch[1] : null,
        firmwareVersion: firmwareMatch ? firmwareMatch[1] : null,
        wifiStatus: wifiStatusMatch ? wifiStatusMatch[1] : null
      };
      
      console.log('提取的设备参数:', deviceParams);
      
      // 更新设备信息对象，确保UI显示最新信息
      if (deviceParams.macAddress && deviceInfo.value) {
        deviceInfo.value = {
          ...deviceInfo.value,
          macAddress: deviceParams.macAddress,
          productId: deviceParams.productId
        };
      }
      
      // 验证关键参数是否存在
      const hasRequiredParams = 
        deviceParams.productId && 
        deviceParams.macAddress && 
        deviceParams.firmwareVersion;
      
      // 灵活处理WiFi状态
      const isWiFiReady = 
        deviceParams.wifiStatus === 'on' || // 显式WiFi连接成功
        deviceParams.wifiStatus === null;   // 允许WiFi状态为空
      
      if (hasRequiredParams) {
        console.log('所有必要参数都已获取，准备注册设备');
        
        // 显示获取信息成功提示
        uni.showToast({
          title: '获取设备信息成功',
          icon: 'success',
          duration: 1500
        });
        
        // 准备注册所需参数
        const registrationData = {
          productId: deviceParams.productId,
          macAddress: deviceParams.macAddress,
          firmwareVersion: deviceParams.firmwareVersion || 'V1.0.0',
          ipAddress: deviceInfo.value?.ipAddress || '',
          wifiSsid: wifiForm.value.ssid || '',
          wifiSignal: deviceInfo.value?.RSSI || -80,
          // 明确标记WiFi状态
          wifiStatus: deviceParams.wifiStatus === 'on'
        };
        
        // 稍微延迟调用注册方法，让用户能看到获取成功提示
        setTimeout(() => {
          // 如果设备正常连接WiFi，进行注册
          if (isWiFiReady) {
            registerDevice(registrationData);
          } else {
            // WiFi未连接但有设备信息，提示用户配网
            isLoading.value = false;
            uni.showModal({
              title: '提示',
              content: '设备WiFi未连接，是否先进行WiFi配置？',
              success: (res) => {
                if (res.confirm) {
                  // 用户选择配网，保存设备信息等待后续配网
                  showWifiList.value = true;
                } else {
                  // 用户选择不配网，直接注册设备
                  registerDevice(registrationData);
                }
              }
            });
          }
        }, 1500);
      } else {
        console.log('参数不完整:', {
          productId: !!deviceParams.productId,
          macAddress: !!deviceParams.macAddress,
          firmwareVersion: !!deviceParams.firmwareVersion
        });
        
        // 显示参数缺失提示
        isLoading.value = false;
        
        // 确定缺少哪些参数并明确提示
        let missingParams = [];
        if (!deviceParams.productId) missingParams.push('产品ID');
        if (!deviceParams.macAddress) missingParams.push('MAC地址');
        if (!deviceParams.firmwareVersion) missingParams.push('固件版本');
        
        showErrorMessage(`设备信息不完整，缺少${missingParams.join('、')}，请重试`);
      }
      
      return;
    }
    
    // 处理WiFi连接成功的其他响应
    if (strData.includes('Network connected!') || 
        strData.includes('SYSEVT_WIFI_CONNECTTED') || 
        strData.includes('dhcp done') || 
        strData.includes('ip:')) {
      console.log('检测到WiFi连接成功');
      
      // 用户通知
      uni.showToast({
        title: 'WiFi连接成功',
        icon: 'success',
        duration: 2000
      });
      
      console.log('WiFi连接成功，等待设备完整信息...');
      
      // 尝试请求完整设备信息
      setTimeout(() => {
        if (connected.value && deviceInfo.value) {
          console.log('尝试请求设备完整信息');
          sendCommand('status').catch(err => {
            console.error('发送状态命令失败:', err);
          });
        }
      }, 2000);
    } 
    // 处理WiFi状态报告
    else if (strData.includes('local:') || strData.includes('sta:')) {
      parseWifiStatusReport(strData);
    } 
    // 处理WiFi列表响应
    else if (strData.startsWith(RESPONSE.WIFI_LIST)) {
      console.log('匹配到WiFi列表响应');
      parseWifiList(strData.substring(RESPONSE.WIFI_LIST.length));
    } 
    // 处理配网结果响应
    else if (strData.startsWith(RESPONSE.CONFIG_RESULT)) {
      console.log('匹配到配网结果响应');
      parseConfigResult(strData.substring(RESPONSE.CONFIG_RESULT.length));
    } 
    // 处理未知响应
    else {
      console.warn('收到未知响应:', strData);
      tryAlternateParsingMethod(strData);
    }
  } catch (error) {
    console.error('解析设备数据失败:', error);
    isLoading.value = false;
    // 确保不会因为解析错误而阻塞用户操作
    showErrorMessage('解析设备数据时出现错误，请重试');
  }
};

// 当收到设备信息时的处理函数
function handleDeviceInfo(infoText) {
  if (infoText.includes('wifi:on') || infoText.includes('wifiStatus:true')) {
    // 显示成功提示
    uni.showToast({
      title: '已成功添加设备',
      icon: 'success',
      duration: 2000
    });
    
    // 解析设备信息
    const productIdMatch = infoText.match(/product_id:([^,]+)/);
    const macMatch = infoText.match(/MAC:([^,]+)/);
    const firmwareMatch = infoText.match(/firmware_version:([^,]+)/);
    
    if (productIdMatch && macMatch) {
      const deviceParams = {
        productId: productIdMatch[1],
        macAddress: macMatch[1],
        firmwareVersion: firmwareMatch ? firmwareMatch[1] : 'V1.0.0',
        ipAddress: '', // 可能需要从其他地方获取
        wifiSsid: '', // 可能需要从其他地方获取
        wifiSignal: -80 // 默认值
      };
      
      // 调用设备注册方法
      registerDevice(deviceParams);
    } else {
      console.error('无法解析完整的设备信息');
    }
  }
}

/**
 * 注册设备到后端
 * @param {Object} deviceParams 设备参数
 */
const registerDevice = async (deviceParams) => {
  try {
    // 防止重复注册
    if (isRegistering.value) {
      console.log('设备已在注册过程中，忽略重复请求');
      return;
    }
    
    console.log('开始注册设备:', deviceParams);
    isRegistering.value = true; 
    isLoading.value = true;
    loadingText.value = '正在注册设备...';
    
    try {
      const registeredDevice = await hardwareStore.registerDevice(deviceParams);
      
      if (registeredDevice) {
        // 成功处理
        console.log('设备注册成功:', registeredDevice);
        
        uni.showToast({
          title: '设备注册成功',
          icon: 'success',
          duration: 2000
        });
        
        // 延迟处理
        setTimeout(() => {
          isLoading.value = false;
          isRegistering.value = false;
          
          // 断开蓝牙连接
          if (connected.value && deviceInfo.value) {
            try {
              disconnectDevice(false);
            } catch (err) {
              console.error('断开设备连接失败:', err);
            }
          }
          
          // 跳转到设备列表
          uni.switchTab({
            url: '/pages/discover/discover',
            success: () => {
              uni.$emit('refresh-device-list');
            }
          });
        }, 2000);
      }
    } catch (error) {
      console.error('设备注册请求失败:', error);
      
      // 错误处理
      let errorMsg = '设备注册失败';
      if (error.message && error.message.includes('已被用户ID为')) {
        // 处理设备已被其他用户绑定的情况
        errorMsg = '设备已被其他用户添加，请联系解绑';
        
        // 立即停止加载状态
        isLoading.value = false;
        isRegistering.value = false;
        
        // 显示错误提示
        uni.showModal({
          title: '添加设备失败',
          content: errorMsg,
          showCancel: false,
          success: () => {
            // 断开蓝牙连接 - 使用更安全的检查
            if (connected.value && deviceInfo.value && deviceInfo.value.deviceId) {
              try {
                disconnectDevice(false);
              } catch (err) {
                console.error('断开设备连接失败:', err);
              }
            }
            
            // 跳转到设备列表页面
            uni.switchTab({
              url: '/pages/discover/discover',
              success: () => {
                uni.$emit('refresh-device-list');
              }
            });
          }
        });
        
        // 提前返回，避免继续执行后续代码
        return;
      } else if (error.message && error.message.includes('超时')) {
        errorMsg = '网络请求超时，请检查网络连接';
        showErrorMessage(errorMsg);
      } else {
        showErrorMessage(errorMsg);
      }
    }
  } catch (error) {
    console.error('设备注册处理失败:', error);
    showErrorMessage('设备注册处理失败');
  } finally {
    isLoading.value = false;
    isRegistering.value = false;
  }
};

// 新增WiFi状态报告解析方法
const parseWifiStatusReport = (report) => {
  try {
    console.log('解析WiFi状态报告:', report);
    
    // 提取MAC地址
    const macMatch = report.match(/local:([\w:]+)/);
    const macAddress = macMatch ? macMatch[1] : '未知';
    
    // 提取信号强度
    const rssiMatch = report.match(/rssi:(-?\d+)/);
    const rssi = rssiMatch ? parseInt(rssiMatch[1]) : -100;
    
    // 提取温度
    const tempMatch = report.match(/chip-temperature: (\d+)/);
    const temperature = tempMatch ? parseInt(tempMatch[1]) : null;
    
    // 提取吞吐量
    const txMatch = report.match(/tx: (\d+\.\d+) Kbps/);
    const txThroughput = txMatch ? parseFloat(txMatch[1]) : 0;
    const rxMatch = report.match(/rx: (\d+\.\d+) Kbps/);
    const rxThroughput = rxMatch ? parseFloat(rxMatch[1]) : 0;
    
    // 更新设备信息
    deviceInfo.value = {
      ...deviceInfo.value,
      wifiStatus: {
        macAddress,
        rssi,
        temperature,
        txThroughput,
        rxThroughput,
        rawReport: report
      }
    };
    
    console.log('WiFi状态更新:', deviceInfo.value.wifiStatus);
  } catch (error) {
    console.error('解析WiFi状态报告失败:', error);
  }
}

// 尝试不同的解析方式
const tryAlternateParsingMethod = (hexData) => {
  console.log('尝试备用解析方法');
  try {
    const networks = [];
    // 假设数据没有网络数量头，而是直接从SSID长度开始
    // 或者数据格式是[SSID][RSSI][安全性]重复
    
    let offset = 0;
    while (offset + 2 <= hexData.length) {
      const ssidLength = parseInt(hexData.substr(offset, 2), 16);
      offset += 2;
      
      if (ssidLength <= 0 || ssidLength > 32 || offset + ssidLength * 2 > hexData.length) {
        break;
      }
      
      const ssidHex = hexData.substr(offset, ssidLength * 2);
      const ssid = hexToStr(ssidHex);
      offset += ssidLength * 2;
      
      // 如果还有数据，尝试解析信号强度和加密类型
      let rssi = -70;
      let secureType = 1;
      
      if (offset + 4 <= hexData.length) {
        rssi = parseInt(hexData.substr(offset, 2), 16) - 100;
        offset += 2;
        
        secureType = parseInt(hexData.substr(offset, 2), 16);
        offset += 2;
      }
      
      console.log(`备用解析: WiFi: ${ssid}, 信号: ${rssi}, 加密类型: ${secureType}`);
      
      networks.push({
        ssid,
        rssi,
        secure: secureType > 0
      });
    }
    
    if (networks.length > 0) {
      console.log(`备用解析完成，共找到 ${networks.length} 个网络:`, networks);
      wifiList.value = networks;
    } else {
      console.log('备用解析也未找到网络');
    }
    
    isScanning.value = false;
  } catch (error) {
    console.error('备用解析失败:', error);
    isScanning.value = false;
  }
}

const parseConfigResult = (hexData) => {
  // 解析配网结果
  // 格式: [状态码][可选信息]
  try {
    console.log('解析配网结果:', hexData)
    const statusCode = hexData.substr(0, 2)
    const success = statusCode === '00'
    
    if (success) {
      uni.showToast({
        title: 'WiFi配置成功',
        icon: 'success',
        duration: 2000
      })
      
      // 更新设备WiFi状态
      deviceInfo.value = {
        ...deviceInfo.value,
        wifiStatus: {
          ...deviceInfo.value?.wifiStatus,
          connected: true,
          ssid: wifiForm.value.ssid,
          lastConnectTime: new Date().toISOString()
        }
      };
      
      // 延迟关闭加载提示，先显示成功提示，再断开连接，最后跳转
      setTimeout(() => {
        isLoading.value = false
        
        // 显示成功提示，让用户知道配置已完成
        uni.showModal({
          title: '配置成功',
          content: '设备已成功连接WiFi，即将返回设备列表',
          showCancel: false,
          success: () => {
            // 重置表单
            wifiForm.value = {
              ssid: '',
              password: ''
            }
            
            // 先断开蓝牙连接，但不显示断开连接的提示
            if (connected.value && deviceInfo.value) {
              // 移除监听
              uni.offBLECharacteristicValueChange(onCharValueChange)
              
              uni.closeBLEConnection({
                deviceId: deviceInfo.value.deviceId,
                success: () => {
                  console.log('蓝牙连接已断开')
                  connected.value = false
                  deviceInfo.value = null
                  
                  // 断开连接后再跳转
                  setTimeout(() => {
                    // 跳转到首页或设备列表页
                    uni.switchTab({
                      url: '/pages/discover/discover'
                    })
                  }, 500)
                },
                fail: (err) => {
                  console.error('断开连接失败:', err)
                  // 即使断开失败也跳转
                  uni.switchTab({
                    url: '/pages/discover/discover'
                  })
                }
              })
            } else {
              // 如果已经断开，直接跳转
              uni.switchTab({
                url: '/pages/discover/discover'
              })
            }
          }
        })
      }, 1000)
    } else {
      // 解析错误信息
      let errorMsg = '配置失败'
      
      switch (statusCode) {
        case '01':
          errorMsg = 'WiFi连接失败，请检查密码是否正确'
          break
        case '02':
          errorMsg = '未找到指定WiFi'
          break
        case '03':
          errorMsg = '设备IP获取失败'
          break
        case '04':
          errorMsg = '服务器连接失败'
          break
        case '05':
          errorMsg = '设备注册失败'
          break
        case '06':  // 新增状态码
          errorMsg = 'WiFi认证失败'
          break
        case '07':  // 新增状态码
          errorMsg = 'WiFi关联失败'
          break
        case '08':  // 新增状态码
          errorMsg = '4次握手失败'
          break
        default:
          errorMsg = '未知错误，错误码: ' + statusCode
      }
      
      // 更新设备WiFi状态
      deviceInfo.value = {
        ...deviceInfo.value,
        wifiStatus: {
          ...deviceInfo.value?.wifiStatus,
          connected: false,
          lastError: errorMsg,
          lastErrorTime: new Date().toISOString()
        }
      };
      
      isLoading.value = false
      showErrorMessage(errorMsg)
    }
  } catch (error) {
    console.error('解析配网结果失败:', error)
    isLoading.value = false
    showErrorMessage('解析配网结果出错，请重试')
  }
}

const disconnectDevice = async (showToast = true) => {
  if (!connected.value || !deviceInfo.value) return
  
  try {
    // 移除监听
    uni.offBLECharacteristicValueChange(onCharValueChange)
    
    await uni.closeBLEConnection({
      deviceId: deviceInfo.value.deviceId
    })
	
    connected.value = false
    deviceInfo.value = null
    
    // 只在需要时显示断开连接的提示
    if (showToast) {
      uni.showToast({
        title: '已断开连接',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('断开连接失败:', error)
    if (showToast) {
      showErrorMessage('断开连接失败，请重试')
    }
  }
}

const sendCommand = async (command) => {
  if (!connected.value || !deviceInfo.value) return false;
  
  try {
    console.log('Sending command:', command, 'size:', command.length);
    
    // Create buffer for the command
    const buffer = new ArrayBuffer(command.length);
    const uint8Array = new Uint8Array(buffer);
    
    // Fill the buffer with the command characters
    for (let i = 0; i < command.length; i++) {
      uint8Array[i] = command.charCodeAt(i);
    }
    
    // Send the command to the device
    return new Promise((resolve, reject) => {
      uni.writeBLECharacteristicValue({
        deviceId: deviceInfo.value.deviceId,
        serviceId: deviceInfo.value.serviceId,
        characteristicId: deviceInfo.value.writeCharId,
        value: buffer,
        success: (res) => {
          console.log('Command sent successfully:', res);
          resolve(true);
        },
        fail: (err) => {
          console.error('Failed to send command:', err);
          reject(err);
        }
      });
    });
  } catch (error) {
    console.error('Error sending command:', error);
    return false;
  }
};

const sendCommandWithRetry = async (command, maxRetries = 3) => {
  let attempt = 0;
  
  while (attempt < maxRetries) {
    try {
      const success = await sendCommand(command);
      if (success) return true;
    } catch (error) {
      console.error(`Attempt ${attempt+1}/${maxRetries} failed:`, error);
      
      // If we've reached the max retries, throw the error
      if (attempt >= maxRetries - 1) {
        throw error;
      }
    }
    
    // Wait before retrying
    await delay(1000);
    attempt++;
  }
  
  return false;
}

const scanWifi = async () => {
  if (isLoading.value) return;
  
  try {
    isScanning.value = true;
    wifiList.value = [];
    showWifiList.value = true;
    
    // 使用微信小程序的WiFi API
    uni.startWifi({
      success: function() {
        console.log('初始化WiFi成功');
        uni.getConnectedWifi({
          success: function(res) {
            console.log('获取当前连接的WiFi成功:', res.wifi);
            // 直接使用当前连接的WiFi
            wifiForm.value.ssid = res.wifi.SSID;
            // 关闭WiFi选择弹窗
            showWifiList.value = false;
            isScanning.value = false;
            
            // 设置加密类型（大多数WiFi都是加密的）
            encryptionIndex.value = 0; // WPA-PSK
            
            uni.showToast({
              title: '已获取当前WiFi',
              icon: 'success'
            });
          },
          fail: function(err) {
            console.error('获取当前连接的WiFi失败:', err);
            isScanning.value = false;
            
            if (err.errCode === 12010) {
              // 用户未打开WiFi
              showErrorMessage('请先打开手机WiFi');
            } else if (err.errCode === 12005) {
              // 用户未授权WiFi信息
              showErrorMessage('请允许小程序获取WiFi信息');
            } else if (err.errCode === 12006) {
              // 当前系统不支持相关能力
              showErrorMessage('当前系统不支持获取WiFi信息');
            } else if (err.errCode === 12009) {
              // 未连接WiFi
              showErrorMessage('请先连接WiFi');
            } else {
              showErrorMessage('获取WiFi信息失败，请手动输入');
            }
          }
        });
      },
      fail: function(err) {
        console.error('初始化WiFi模块失败:', err);
        isScanning.value = false;
        showErrorMessage('WiFi模块初始化失败，请检查权限设置');
      }
    });
  } catch (error) {
    console.error('扫描WiFi失败:', error);
    isScanning.value = false;
    showErrorMessage('获取WiFi信息失败');
  }
}

const selectWifi = (wifi) => {
  wifiForm.value.ssid = wifi.ssid
  showWifiList.value = false
  
  // 根据WiFi加密类型设置默认加密方式
  encryptionIndex.value = wifi.secure ? 0 : 1 // 0=WPA-PSK, 1=NONE
  
  // 如果是开放网络，清空密码
  if (!wifi.secure) {
    wifiForm.value.password = ''
  }
}

const onEncryptionChange = (e) => {
  encryptionIndex.value = e.detail.value
}

const configWifi = async () => {
  if (!connected.value || !deviceInfo.value || !wifiForm.value.ssid) return;
  
  isLoading.value = true;
  loadingText.value = '正在配置WiFi...';
  
  // Set a timeout for the entire process
  const timeout = setTimeout(() => {
    if (isLoading.value) {
      console.log('配网超时，检查设备状态');
      isLoading.value = false;
      uni.showModal({
        title: '提示',
        content: '配网超时，请检查设备状态并重试',
        showCancel: false
      });
    }
  }, 30000); // 30 second timeout
  
  try {
    // Check connection status first
    if (!connected.value) {
      console.log('设备已断开，尝试重新连接');
      try {
        await connectWithRetry(deviceInfo.value);
        console.log('重新连接成功');
      } catch (err) {
        console.error('重新连接失败:', err);
        clearTimeout(timeout);
        isLoading.value = false;
        showErrorMessage('设备连接已断开，请重新连接');
        return;
      }
    }
    
    // Ensure correct format with the colon prefix
    const command = `:${wifiForm.value.ssid},${wifiForm.value.password},${encryptionIndex.value === 1 ? '0' : '1'}`;
    
    console.log('发送WiFi配置命令:', command);
    
    try {
      // Use retry logic when sending the command
      const success = await sendCommandWithRetry(command, 3);
      
      if (success) {
        uni.showToast({
          title: '命令已发送',
          icon: 'success'
        });
        
        // 更新加载文本
        loadingText.value = '等待设备连接WiFi...';
        
        // 等待设备响应，10秒后检查状态
        setTimeout(() => {
          if (isLoading.value) {
            console.log('尝试主动获取设备状态');
            sendCommand('status').catch(err => {
              console.log('发送状态命令失败:', err);
            });
            
            // 再等待10秒
            setTimeout(() => {
              if (isLoading.value) {
                // 如果还在加载，关闭加载
                clearTimeout(timeout);
                isLoading.value = false;
                
                // 询问用户是否成功
                uni.showModal({
                  title: '提示',
                  content: '未收到设备WiFi连接成功通知，设备可能已连接但未能获取状态，是否继续?',
                  success: (res) => {
                    if (res.confirm) {
                      // 用户确认，尝试注册设备
                      if (deviceInfo.value && deviceInfo.value.macAddress && deviceInfo.value.productId) {
                        const params = {
                          productId: deviceInfo.value.productId || '',
                          macAddress: deviceInfo.value.macAddress,
                          firmwareVersion: deviceInfo.value.firmwareVersion || 'V1.0.0',
                          wifiStatus: true,
                          wifiSsid: wifiForm.value.ssid,
                          ipAddress: deviceInfo.value?.ipAddress || '',
                          wifiSignal: deviceInfo.value?.RSSI || -80
                        };
                        registerDevice(params);
                      } else {
                        showErrorMessage('缺少设备信息，无法注册');
                      }
                    }
                  }
                });
              }
            }, 10000);
          }
        }, 10000);
      } else {
        clearTimeout(timeout);
        isLoading.value = false;
        showErrorMessage('发送命令失败，请重试');
      }
    } catch (error) {
      clearTimeout(timeout);
      console.error('配置WiFi失败:', error);
      isLoading.value = false;
      showErrorMessage('配置WiFi失败, 错误码: ' + (error.errCode || '未知'));
    }
  } catch (error) {
    clearTimeout(timeout);
    console.error('配置WiFi失败:', error);
    isLoading.value = false;
    showErrorMessage('配置WiFi失败');
  }
};

// 修改测试函数
const testScanWifi = async () => {
  try {
    console.log('测试扫描WiFi命令');
    // 使用扫描命令
    const cmd = CMD.SCAN_WIFI;
    const success = await sendCommand(cmd);
    
    if (success) {
      // 直接显示测试WiFi列表
      wifiList.value = [
        { ssid: 'UPGRADE-AP', rssi: -55, secure: false },
        { ssid: 'KuWiFi', rssi: -65, secure: true },
        { ssid: 'TEST-WIFI', rssi: -70, secure: true }
      ];
      showWifiList.value = true;
      isScanning.value = false;
      
      uni.showToast({
        title: '测试命令已发送',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('测试命令发送失败:', error);
  }
};

const testAlternateCommand = async () => {
  try {
    console.log('发送备用扫描命令');
    // 直接发送测试配网命令
    const cmd = ':UPGRADE-AP,TEST1234,1';
    const success = await sendCommand(cmd);
    
    if (success) {
      uni.showToast({
        title: '备用命令已发送',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('备用命令发送失败:', error);
  }
};

// 添加直接选择测试WiFi的函数
const selectTestWifi = () => {
  // 直接选择UPGRADE-AP作为测试WiFi
  wifiForm.value.ssid = 'UPGRADE-AP';
  // 设置为WPA-PSK加密
  encryptionIndex.value = 0; // 0=WPA-PSK
  wifiForm.value.password = 'TEST1234';
  
  uni.showToast({
    title: '已选择测试WiFi',
    icon: 'none'
  });
};

const configUpgradeAP = async () => {
  isLoading.value = true;
  loadingText.value = '正在配置WiFi...';
  
  try {
    // 固定测试命令
    const cmd = ':UPGRADE-AP,TEST1234,1';
    console.log('发送配置命令:', cmd);
    
    const success = await sendCommand(cmd);
    
    if (success) {
      uni.showToast({
        title: '配置命令已发送',
        icon: 'success'
      });
      
      // 设置超时处理
      setTimeout(() => {
        if (isLoading.value) {
          isLoading.value = false;
          uni.showToast({
            title: '配置成功',
            icon: 'success'
          });
        }
      }, 3000);
    } else {
      isLoading.value = false;
      showErrorMessage('发送命令失败');
    }
  } catch (error) {
    console.error('配置失败:', error);
    isLoading.value = false;
    showErrorMessage('配置失败');
  }
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
</script>
	
	

<style lang="scss">
.blue-wifi-container {
  min-height: 100vh;
  background-color: #F5F5F5;
  position: relative;
  
  // 状态卡片
  .status-card {
    margin: 30rpx;
    padding: 30rpx;
    background: #fff;
    border-radius: 16rpx;
    display: flex;
    align-items: center;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
    
    .status-icon {
      width: 100rpx;
      height: 100rpx;
      border-radius: 50%;
      background: #f1f5ff;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 30rpx;
      transition: all 0.3s ease;
      
      image {
        width: 60rpx;
        height: 60rpx;
      }
      
      &.connected {
        background: #e6f7ff;
        animation: pulse 1.5s infinite;
      }
    }
    
    .status-text {
      flex: 1;
      
      .status-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 8rpx;
      }
      
      .status-desc {
        font-size: 26rpx;
        color: #999;
      }
    }
  }
  
  // 设备列表
  .device-list {
    margin: 30rpx;
    padding: 20rpx 0;
    background: #fff;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
    
    .section-title {
      font-size: 32rpx;
      font-weight: 500;
      color: #333;
      padding: 20rpx 30rpx;
      border-bottom: 1rpx solid #f5f5f5;
    }
    
    .device-item {
      padding: 24rpx 30rpx;
      border-bottom: 1rpx solid #f5f5f5;
      transition: background-color 0.3s;
      
      &:active {
        background-color: #f9f9f9;
      }
      
      &:last-child {
        border-bottom: none;
      }
      
      .device-name {
        font-size: 30rpx;
        font-weight: 500;
        color: #333;
        margin-bottom: 10rpx;
      }
      
      .device-info {
        display: flex;
        justify-content: space-between;
        font-size: 24rpx;
        color: #999;
        
        .device-id {
          flex: 1;
          font-family: monospace;
        }
        
        .rssi {
          flex-shrink: 0;
          margin-left: 20rpx;
          background: #f5f5f5;
          padding: 4rpx 12rpx;
          border-radius: 20rpx;
        }
      }
    }
  }
  
  // 设备信息
  .device-info {
    margin: 30rpx;
    padding: 20rpx 0;
    background: #fff;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
    
    .section-title {
      font-size: 32rpx;
      font-weight: 500;
      color: #333;
      padding: 20rpx 30rpx;
      border-bottom: 1rpx solid #f5f5f5;
    }
    
    .info-list {
      .info-item {
        display: flex;
        padding: 24rpx 30rpx;
        border-bottom: 1rpx solid #f5f5f5;
        
        &:last-child {
          border-bottom: none;
        }
        
        .label {
          width: 160rpx;
          font-size: 28rpx;
          color: #666;
        }
        
        .value {
          flex: 1;
          font-size: 28rpx;
          color: #333;
          
          &.uuid {
            font-family: monospace;
            color: #666;
            word-break: break-all;
          }
        }
      }
    }
  }
  
  // WiFi配置表单
  .wifi-form {
    margin: 30rpx;
    padding: 20rpx 0;
    background: #fff;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
    
    .section-title {
      font-size: 32rpx;
      font-weight: 500;
      color: #333;
      padding: 20rpx 30rpx;
      border-bottom: 1rpx solid #f5f5f5;
    }
    
    .input-group {
      padding: 24rpx 30rpx;
      display: flex;
      align-items: center;
      border-bottom: 1rpx solid #f5f5f5;
      
      .input-label {
        width: 160rpx;
        font-size: 28rpx;
        color: #666;
      }
      
      input, .picker {
        flex: 1;
        height: 60rpx;
        font-size: 28rpx;
        color: #333;
      }
      
      .picker {
        line-height: 60rpx;
      }
      
      .input-icon {
        width: 60rpx;
        display: flex;
        justify-content: center;
        
        .iconfont {
          font-size: 40rpx;
          color: #999;
        }
      }
    }
    
    .config-btn {
      width: 90%;
      height: 88rpx;
      margin: 40rpx auto 20rpx;
      background: #5677fc;
      color: #fff;
      font-size: 32rpx;
      border-radius: 44rpx;
      box-shadow: 0 6rpx 20rpx rgba(86, 119, 252, 0.2);
      
      &:disabled {
        opacity: 0.6;
      }
    }

    // 调试按钮
  .debug-btns {
    display: flex;
    justify-content: space-between;
    padding: 0 30rpx;
    margin-top: 20rpx;
    margin-bottom: 20rpx;
    
    .debug-btn, .system-btn {
      flex: 1;
      height: 80rpx;
      font-size: 28rpx;
      margin: 0 10rpx;
      background: #f0f0f0;
      color: #666;
      border-radius: 40rpx;
      line-height: 80rpx;
      
      &:active {
        background: #e0e0e0;
      }
    }
    
    .debug-btn {
      background: #f5f5f5;
    }
    
    .system-btn {
      background: #e6f7ff;
    }
  }


  }
  
  // 初始化按钮
  .init-btn {
    width: 90%;
    height: 88rpx;
    margin: 40rpx auto;
    background: #5677fc;
    color: #fff;
    font-size: 32rpx;
    border-radius: 44rpx;
    box-shadow: 0 6rpx 20rpx rgba(86, 119, 252, 0.2);
    
    &:disabled {
      opacity: 0.6;
    }
  }
  
  // 调试按钮
  .debug-btns {
    display: flex;
    justify-content: space-between;
    padding: 0 30rpx;
    margin-top: 20rpx;
    
    .debug-btn, .system-btn {
      flex: 1;
      height: 80rpx;
      font-size: 28rpx;
      margin: 0 10rpx;
      background: #f0f0f0;
      color: #666;
      border-radius: 40rpx;
      line-height: 80rpx;
      
      &:active {
        background: #e0e0e0;
      }
    }
    
    .debug-btn {
      background: #f5f5f5;
    }
    
    .system-btn {
      background: #e6f7ff;
    }
  }
  
  // WiFi列表弹窗
  .wifi-popup {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1000;
    
    .wifi-popup-mask {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5);
    }
    
    .wifi-popup-content {
      position: absolute;
      left: 30rpx;
      right: 30rpx;
      bottom: 50rpx;
      background: #fff;
      border-radius: 16rpx;
      overflow: hidden;
      max-height: 80vh;
      display: flex;
      flex-direction: column;
      animation: slideUp 0.3s ease-out;
      
      .wifi-popup-header {
        padding: 30rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1rpx solid #f5f5f5;
        
        .wifi-popup-title {
          font-size: 32rpx;
          font-weight: 600;
          color: #333;
        }
        
        .wifi-popup-close {
          font-size: 40rpx;
          color: #999;
          line-height: 1;
        }
      }
      
      .wifi-list {
        flex: 1;
        max-height: 60vh;
        
        .scanning-tips, .empty-tips {
          padding: 60rpx 0;
          text-align: center;
          color: #999;
          display: flex;
          flex-direction: column;
          align-items: center;
          
          .loading-spinner {
            width: 60rpx;
            height: 60rpx;
            border: 4rpx solid #f3f3f3;
            border-top: 4rpx solid #5677fc;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 20rpx;
          }
          
          .refresh-btn {
            margin-top: 20rpx;
            padding: 10rpx 30rpx;
            font-size: 26rpx;
            color: #5677fc;
            background: rgba(86, 119, 252, 0.1);
            border-radius: 30rpx;
            border: none;
          }
        }
        
        .wifi-item {
          padding: 30rpx;
          border-bottom: 1rpx solid #f5f5f5;
          
          &:active {
            background-color: #f9f9f9;
          }
          
          .wifi-name {
            font-size: 30rpx;
            color: #333;
            margin-bottom: 10rpx;
          }
          
          .wifi-desc {
            display: flex;
            align-items: center;
            
            .wifi-strength {
              height: 6rpx;
              background: linear-gradient(to right, #5677fc, #38a0ff);
              border-radius: 3rpx;
              margin-right: 20rpx;
            }
            
            .wifi-secure {
              font-size: 24rpx;
              color: #999;
              padding: 4rpx 12rpx;
              background: #f5f5f5;
              border-radius: 20rpx;
            }
          }
        }
      }
    }
  }
  
  // 加载遮罩
  .loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.6);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 2000;
    
    .loading-content {
      width: 220rpx;
      height: 220rpx;
      background: rgba(0, 0, 0, 0.8);
      border-radius: 20rpx;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      
      .loading-spinner {
        width: 60rpx;
        height: 60rpx;
        border: 4rpx solid rgba(255, 255, 255, 0.3);
        border-top: 4rpx solid #fff;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin-bottom: 20rpx;
      }
      
      .loading-text {
        font-size: 28rpx;
        color: #fff;
        text-align: center;
        padding: 0 20rpx;
      }
    }
  }
  
  // 错误提示模态框
  .error-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.6);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 2000;
    
    .error-content {
      width: 80%;
      background: #fff;
      border-radius: 20rpx;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      
      .error-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
        padding: 30rpx;
        text-align: center;
        border-bottom: 1rpx solid #f5f5f5;
      }
      
      .error-message {
        padding: 40rpx 30rpx;
        font-size: 28rpx;
        color: #666;
        text-align: center;
        line-height: 1.5;
      }
      
      .error-btn {
        height: 88rpx;
        line-height: 88rpx;
        font-size: 32rpx;
        color: #5677fc;
        text-align: center;
        border-top: 1rpx solid #f5f5f5;
      }
    }
  }
  
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
  
  @keyframes slideUp {
    from { transform: translateY(100%); }
    to { transform: translateY(0); }
  }
  
  @keyframes pulse {
    0% { box-shadow: 0 0 0 0 rgba(86, 119, 252, 0.4); }
    70% { box-shadow: 0 0 0 10px rgba(86, 119, 252, 0); }
    100% { box-shadow: 0 0 0 0 rgba(86, 119, 252, 0); }
  }
}
</style>